#!/usr/bin/python
'''
/*
 * This computer program is the confidential information and proprietary trade
 * secret of VistaraIT LLC.  Possessions and use of this program must  conform
 * strictly to the license agreement between the user and VistaraIT LLC.,  and
 * receipt or possession does not convey any rights to divulge, reproduce,  or
 * allow others to use this program without specific written authorization  of
 * VistaraIT LLC.
 * 
 * Copyright (c) 2014 VistaraIT, Inc. All rights reserved.
 */
'''

from ConfigParser import ConfigParser
#import dateutils, datetime

class ConfigManager(object):
    
    #configuration file
    _conf_file = '/home/admin/data/config.properties'

    #config
    APPLIANCE_TITLE='appliance.title'
    CONFIG_UPDATE_SERVER_PROTOCOL='update.server.protocol'
    CONFIG_ALERT_SERVER_HOST='alert.server.host'
    SESSION_FILE = 'session.file'
    SESSION_TIME_FILE = 'session.time.file'
    SESSION_TIMEOUT = 'session.timeout'
    PYTHON_CMD = 'python.command'
    DEBUG_INFO_FILE = 'debug_info_file'

    '''
    #license-rechability
    LICENSE_ID_INSTALLED = 'license.id.installed'
    LICENSE_STOP_COUNT = 'license.stop.count'
    LICENSE_COUNT = 'failed.count'
    LICENSE_UPDATETIME = 'last.checked.time'
    '''
    
    #network-connection
    NETWORK_CON_TYPE = 'connection.type'
    PROXY_IP='proxy.ip'
    PROXY_PORT='proxy.port'
    PROXY_USR='proxy.user'
    PROXY_PWD='proxy.password'
    
    '''
    REGISTRATION_SAID = 'said'
    REGISTRATION_CLIENT_ID = 'client_id'
    REGISTRATION_DB_ID = 'sa_db_id'
    '''
    
    #tunnel-info
    TUNNEL_STATUS = 'tunnel.status'
    TUNNEL_ESB_TS = 'tunnel.established.time'
    TUNNEL_PORT = 'tunnel.port'
    TUNNEL_SERVER = 'tunnel.server'
    
    #sections
    _section_network='network'
    '''
    _section_license_reachability = 'license-rechability'
    _section_registration='registration'
    '''
    
    _section_tunnel_info = 'tunnel-info'
    
    def __init__(self):
        self.cfg = ConfigParser()
        self.cfg.read(self._conf_file)

    '''
    Gets property from the configuration file
    '''
    def getProperty(self, key):
        try:
            return self.cfg.get("config", key)
        except:
            raise Exception("Failed to get config property[ " + key + " ]")
  
    '''
    Gets property from the configuration file
    '''
    def getRegistrationProperty(self, key):
        try:
            return self.cfg.get(self._section_registration, key)
        except:
            raise Exception("Failed to get config property[ " + key + " ]")

    '''
    Gets property from configuration file from a given section
    '''
    def getSectionProperty(self, section, key):
        try:
            return self.cfg.get(section, key)
        except:
            raise Exception("Failed to get the property[ " + key + " ]")

  
    '''
    Update the config.properties file section license reachability
    '''
    '''
    def saveLicenseReachability(self, reset=False, id=0):
        count = 0
        last_modified_time = dateutils.getCurrentTimeAsString()
        try:
            count = int(self.getLicenseReachabilityProperty(self.LICENSE_COUNT))
        except:
            pass

        try:
            last_modified_time = dateutils.convertStringTODate(self.getLicenseReachabilityProperty(self.LICENSE_UPDATETIME))
        except:
            pass

        current_time = dateutils.getCurrentTimeAsString()
        
        try:
            if reset:
                self.cfg.set(self._section_license_reachability, self.LICENSE_ID_INSTALLED, str(id))
                self.cfg.set(self._section_license_reachability, self.LICENSE_COUNT, str(0))
                self.cfg.set(self._section_license_reachability, self.LICENSE_UPDATETIME, str(current_time))
                self._saveConfigurations()
            elif dateutils.getDateDiffInDays(current_time, last_modified_time) > datetime.timedelta(seconds=0):
                self.cfg.set(self._section_license_reachability, self.LICENSE_ID_INSTALLED, str(id))
                self.cfg.set(self._section_license_reachability, self.LICENSE_COUNT, str(count+1))
                self.cfg.set(self._section_license_reachability, self.LICENSE_UPDATETIME, str(current_time))
                self._saveConfigurations()
        except:
            raise Exception("Failed to update the license properties")
       
    '''     
    '''
    Save current configurations to a file
    '''
    def _saveConfigurations(self):
        with open(self._conf_file, 'wb') as configfile:
            self.cfg.write(configfile)
        
    '''
    Gets property from configuration file from section license-rechability
    def getLicenseReachabilityProperty(self, key):
        try:
            return self.cfg.get(self._section_license_reachability, key)
        except:
            raise Exception("Failed to get license-rechability property[ " + key + " ]")
        
        
    Gets property from configuration file from section tunnel
    '''
    def getTunnelInfoProperty(self, key):
        try:
            return self.cfg.get(self._section_tunnel_info, key)
        except:
            raise Exception("Failed to get tunnel-info property[ " + key + " ]")

    '''
    Gets property from configuration file from section network
    '''
    def getProxyProperties(self, key):
        try:
            return self.cfg.get(self._section_network, key)
        except:
            raise Exception("Failed to get network property[ " + key + " ]")

    '''
    Update the "tunnel-info" section properties in configuration file
    ''' 
    def updateTunnelInfo(self, status='', ts='', server='', port=''):
        self.cfg.set(self._section_tunnel_info, self.TUNNEL_STATUS, str(status))
        self.cfg.set(self._section_tunnel_info, self.TUNNEL_ESB_TS, str(ts))
        self.cfg.set(self._section_tunnel_info, self.TUNNEL_SERVER, str(server))
        self.cfg.set(self._section_tunnel_info, self.TUNNEL_PORT, str(port))
        self._saveConfigurations()

    '''
    Update the "network" section properties in configuration file
    '''
    def setProxySetting(self, con_type, proxy_ip='', proxy_port='', proxy_usr='', proxy_pwd=''):
        self.cfg.set(self._section_network, self.NETWORK_CON_TYPE, str(con_type))
        self.cfg.set(self._section_network, self.PROXY_IP, str(proxy_ip))
        self.cfg.set(self._section_network, self.PROXY_PORT, str(proxy_port))
        self.cfg.set(self._section_network, self.PROXY_USR, str(proxy_usr))
        self.cfg.set(self._section_network, self.PROXY_PWD, str(proxy_pwd))
        self._saveConfigurations()
    
    '''
    Update the given section properties in configuration file
    ''' 
        
    def updateSectionProperties(self, section, propList={}):
        for key, value in propList.iteritems():
            self.cfg.set(section, key, str(value))
        self._saveConfigurations()

    def updateMultipleSectionProperties(self, properties={}):
        for section, propHash in properties.iteritems():
            for key, value in propHash.iteritems():
                self.cfg.set(section, key, str(value))
        self._saveConfigurations()
